<template>
  <div class="machine-manage">
    <el-card>
      <div class="card-header">
        <h2>机器管理</h2>
        <el-button type="primary" @click="showAddMachineDialog = true"
          >添加机器</el-button
        >
      </div>

      <el-table :data="machines" border v-loading="loading">
        <el-table-column prop="id_" label="ID" width="80"></el-table-column>
        <el-table-column
          prop="machine_number"
          label="机器编号"
        ></el-table-column>
        <el-table-column label="所属机房">
          <template #default="scope">
            <el-tag>{{
              getRoomNameById(scope.row.room_id)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ statusMap[scope.row.status] || scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              @click="handleChangeStatus(scope.row)"
              :disabled="scope.row.status === 'in_use'"
            >
              {{ scope.row.status === "available" ? "标记故障" : "恢复正常" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加机器对话框 -->
    <el-dialog
      title="添加机器"
      v-model="showAddMachineDialog"
      @close="resetMachineForm"
    >
      <el-form :model="newMachine" :rules="machineRules" ref="machineFormRef">
        <el-form-item label="机器编号" prop="machine_number">
          <el-input
            v-model="newMachine.machine_number"
            placeholder="请输入机器编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属机房" prop="room_id">
          <el-select
            v-model="newMachine.room_id"
            placeholder="请选择机房"
            clearable
          >
            <el-option
              v-for="room in rooms"
              :key="room.id_"
              :label="room.name"
              :value="room.id_"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddMachineDialog = false">取消</el-button>
        <el-button type="primary" @click="addMachine" :loading="adding"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  getMachines,
  createMachine,
  updateMachineStatus,
} from "../api/machine";
import { getComputerRooms, getComputerRoomById } from "../api/rooms";
import { ElMessage, ElMessageBox } from "element-plus";

// 响应式数据
const machines = ref([]);
const rooms = ref([]);
const loading = ref(false);
const adding = ref(false);

const showAddMachineDialog = ref(false);

const newMachine = ref({
  machine_number: "",
  room_id: null,
});

// 状态映射
const statusMap = {
  available: "正常",
  in_use: "使用中",
  maintenance: "故障",
};

// 表单引用
const machineFormRef = ref(null);

// 验证规则
const machineRules = ref({
  machine_number: [
    { required: true, message: "请输入机器编号", trigger: "blur" },
    {
      min: 1,
      max: 20,
      message: "机器编号长度在 1 到 20 个字符",
      trigger: "blur",
    },
  ],
  room_id: [{ required: true, message: "请选择所属机房", trigger: "change" }],
});

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    available: "success",
    in_use: "warning",
    maintenance: "danger",
  };
  return typeMap[status] || "info";
};

const getRoomNameById = (roomId) => {
  if (!roomId) return "未知";
  const room = rooms.value.find((room) => room.id_ === roomId);
  return room ? room.name : "未知";
};

// 获取机器列表
const fetchMachines = async () => {
  loading.value = true;
  try {
    const response = await getMachines();
    machines.value = response.data;
  } catch (error) {
    ElMessage.error(
      "获取机器列表失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取机器列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取机房列表（用于添加机器时选择）
const fetchRooms = async () => {
  try {
    const response = await getComputerRooms();
    console.log("机房列表:", response.data);
    rooms.value = response.data;
  } catch (error) {
    ElMessage.error(
      "获取机房列表失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取机房列表失败:", error);
  }
};

// 重置机器表单
const resetMachineForm = () => {
  newMachine.value = {
    machine_number: "",
    room_id: null,
  };
  machineFormRef.value?.clearValidate();
};

// 添加机器
const addMachine = async () => {
  if (!machineFormRef.value) return;

  try {
    await machineFormRef.value.validate();
    adding.value = true;

    await createMachine(newMachine.value);
    ElMessage.success("添加机器成功");
    showAddMachineDialog.value = false;
    await fetchMachines();
  } catch (error) {
    if (error.errors) {
      // 验证错误，不需要显示错误消息
      return;
    }
    ElMessage.error(
      "添加机器失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("添加机器失败:", error);
  } finally {
    adding.value = false;
  }
};

// 改变机器状态（正常/故障）
const handleChangeStatus = async (machine) => {
  const newStatus =
    machine.status === "available" ? "maintenance" : "available";
  const confirmMessage =
    machine.status === "available"
      ? `确定要将机器 ${machine.machine_number} 标记为故障吗？`
      : `确定要将机器 ${machine.machine_number} 恢复为正常状态吗？`;

  try {
    await ElMessageBox.confirm(confirmMessage, "确认操作", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    console.log(`更新机器 ${machine.id_} 状态为: ${newStatus}`);

    await updateMachineStatus(machine.id_, newStatus);

    ElMessage.success(`机器状态已更新为${statusMap[newStatus]}`);
    await fetchMachines();
  } catch (error) {
    if (error === "cancel") {
      // 用户取消操作，不需要显示错误消息
      return;
    }
    ElMessage.error(
      "更新机器状态失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("更新机器状态失败:", error);
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchMachines();
  fetchRooms();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.machine-manage {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}
</style>
